var addrCode="";
var imgList=[];
var farmImages="";
var addrDetail="";
var describ="";
var enumCategoryid="";
var faLevel="";
var faName="";
var lat="";
var lon="";
var sca="";
var usca="";
var addrName="";
var biaozi="";
$(document).ready(function() {
    if(AUTH.role!="vimi8_com"&&AUTH.job!="vimi_manager"){
        ShowTip("没有管理农场的权限，请用为米指定账户登录！", "success", 1000);
        setTimeout(function () {
            window.location="login.html" ;
        },1000);
    }
    "use strict";
    var farmId = GetQueryString("id");
    var sheng="520000000000";
    getShi(sheng);
    getFarmCategory();
    _gitFarmByFarmId(farmId);
    "use strict";
    ueEditorInit();
});
function ueEditorInit() {
    var ue = UE.getEditor('container');

    baidu.editor.commands['imgupload'] = {
        execCommand: function () {
            var exec = this;

            $("#uploadImg").modal("show");

            var ossfile = $("#imgUploadWrapper").imgUpload();
            $("#uploadImgConfirm").on("click", function (e) {
                var imgHtml = "";
                if(typeof ossfile.uploaded != 'undefined' && ossfile.uploaded.length > 0) {
                    for(var i = 0; i < ossfile.uploaded.length; i++) {
                        imgHtml += '<img src="'+ ossfile.uploaded[i] +'">';
                    }
                }
                exec.execCommand('insertHtml', imgHtml);

                $("#uploadImg").modal("hide");

                return true;
            });
        },
        queryCommandState: function () {
        }
    };
}



//修改农场
function updateFA(){

if(orgClass!="org_ebb_county"){
    ShowTip("你还没有权限做该操作！请联系管理员", "success", 1000);
     setTimeout(function () {
                                            window.location = "index.html";
                                        }, 1000);
        return ;
}

    addrDetail=$("#add").val();
    var ue = UE.getEditor('container');
    biaozi = ue.getContent();
    describ=$("#brief").val();
    enumCategoryid="["+$("#cate option:selected").val()+"]";
    faLevel=$("#star").val();
    faName=$("#name").val();
    lat=$("#lat").val();
    lon=$("#lon").val();
    sca=$("#scale").val();
    usca=$("#scaleUnit").val();

    if(uploadFile.backFileUrl&&uploadFile.backFileUrl.length>0){
        var str="";
        for (var i=0;i<uploadFile.backFileUrl.length;i++){
            str+=("\""+uploadFile.backFileUrl[i]+"\""+",");
        }
        farmImages="["+str.substring(0,str.length-1)+"]";
    }else {
        farmImages="[]";
    }

 var farmId = GetQueryString("id");
         var data={

                "addressDetail": addrDetail,
                "content":biaozi,
                "des": describ,
                "enumCategoryId": enumCategoryid,
                "farmAddressCode": addrCode,
                "farmImages": farmImages,
                "farmLevel": faLevel,
                "farmName": faName,
                "id": farmId,
                "latitude": lat,
                "longitude": lon,
                "orgClass": "org_farm",
                "scale": sca,
                "uscale": usca
              }

           $.ajax({
               type: "PUT",
               url: "/industrial/farm/",
               data: JSON.stringify(data),
               contentType: "application/json",
               success: function (result) {
                  console.log("修改农场成功");
                   ShowTip("修改农场成功", "success", 1500);
                   setTimeout(function () {
                       window.location="index.html" ;
                   },2000);
               },
               error: function (err) {
                   console.log(err);
                    ShowTip("修改农场失败", "danger", 1000);
               }
           });
}


//查询农场分类
function getFarmCategory(){
     $.ajax({
           type: "get",
           url: "/industrial/category/farmCategoryList",
           dataType: "json",
           async: true,
           success: function(data) {
                var result = data;
                $("#cate").html($.templates("#FarmCategory").render(result));


           }
       });
 }

 function upaCity(){
     shi= $("#twoClassify option:selected").val();
     getQue(shi);
  }

  function upaXian(){
      xian= $("#threeClassify option:selected").val();
      getXZ(xian);
   }

   function upaXiang(){
       xiang= $("#fourClassify option:selected").val();
       getCun(xiang);
     }

//市
function getShi(sheng){
    $.ajax({
        type: "get",
        url: "/portal/geo/?addressCode="+sheng,
        dataType: "json",
        async: true,
        success: function(data) {
            var result = data;
            $("#twoClassify").html($.templates("#twoClassifyTemp").render(result));
            // shi= $("#twoClassify option:selected").val();
            // getQue(shi);

        }
    });
}



//区/县
function getQue(shi){
    $.ajax({
        type: "get",
        url: "/portal/geo/?addressCode="+shi,
        dataType: "json",
        async: true,
        success: function(data) {
            var result = data;
            $("#threeClassify").html($.templates("#threeClassifyTemp").render(result));
            // xian= $("#threeClassify option:selected").val();
            //  getXZ(xian);
        }
    });
}

//乡镇
function getXZ(xian){
    $.ajax({
        type: "get",
        url: "/portal/geo/?addressCode="+xian,
        dataType: "json",
        async: true,
        success: function(data) {
            var result = data;
            $("#fourClassify").html($.templates("#fourClassifyTemp").render(result));
            //   xiang= $("#fourClassify option:selected").val();
            //   getCun(xiang);
        }
    });
}

//村
function getCun(xiang){
    $.ajax({
        type: "get",
        url: "/portal/geo/?addressCode="+xiang,
        dataType: "json",
        async: true,
        success: function(data) {
            var result = data;
            $("#fiveClassify").html($.templates("#fiveClassifyTemp").render(result));
            cun= $("#fiveClassify option:selected").val();
        }
    });
}

//根据id查当前地址
function getNowaddr(idCode){
    $.ajax({
        type: "get",
        url: "/portal/geo/nowAddress?addressCode="+idCode,
        dataType: "json",
        async: true,
        success: function(data) {
           var result=data;
          addrName=result[0].geoName;
           $("#address").val(addrName);

        }
    });
}
    //地址码确认按钮
   function makeSureClassify(){
        var code=$("#fiveClassify option:selected").text();
        $("#address").val(code);
        addrCode=$("#fiveClassify option:selected").val();
        $("#selectCateModal").modal("hide");
   }

function initMap(){
    //输入框
    var lngInput = $("input[name=lng]");
    var latInput = $("input[name=lat]");

    //初始点
    var initLnglat = {
        lng: lon,
        lat: lat
    };

    //初始化地图
    MAP = new AMap.Map('mapContainer', {
        center: [initLnglat.lng, initLnglat.lat],
        zoom: 12
    });
    MAP.plugin(['AMap.ToolBar','AMap.Geolocation'], function() {
        //工具条（缩放、平移、定位）
        MAP.addControl(new AMap.ToolBar({
            offset: new AMap.Pixel(20,100),
            position: "RB",
            locate: true,
            liteStyle: true
        }));
    });

    //初始化地图点
    marker = new AMap.Marker({
        position : new AMap.LngLat(initLnglat.lng, initLnglat.lat),
        animation: "AMAP_ANIMATION_DROP"
    });
    MAP.add(marker);
    lngInput.val(initLnglat.lng);
    latInput.val(initLnglat.lat);

    //地图点击事件
    var _onClick = function(e){
        marker.setPosition(e.lnglat);
        lngInput.val(e.lnglat.lng);
        latInput.val(e.lnglat.lat);
    };
    var clickListener = AMap.event.addListener(MAP, "click", _onClick); //绑定事件，返回监听对象
    //AMap.event.removeListener(clickListener); //移除事件，以绑定时返回的对象作为参数
}

function _gitFarmByFarmId(farmId){
    $.ajax({
        type: "get",
        url: "/industrial/farm/farmInfoOnly?clientId="+farmId,
        dataType: "json",
        async: true,
        success: function(data) {
            if(data!=null&&data!=""){
                imgList=eval(data.farmImages);
                uploadFile.backFileUrl=imgList;
                addrCode=data.farmAddressCode;
                getNowaddr(addrCode);
                addrDetail=data.addressDetail;
                describ=data.des;
                enumCategoryid = eval(data.enumCategoryId);
                enumCategoryid=enumCategoryid&&enumCategoryid.length>0?enumCategoryid[0]:"";
                faLevel=data.farmLevel;
                faName=data.farmName;
                lat=data.latitude;
                lon=data.longitude;
                var dabiaozi=data.content;
                sca=data.scale;
                usca=data.uscale;
                $("#name").val(faName);
                $("#add").val(addrDetail);
                $("#brief").val(describ);
                $("#cate").val(enumCategoryid);
                $("#star").val(faLevel);
                $("#container").val(dabiaozi);
                var tt=  $("#container").val();
                $("#scale").val(sca);
                $("#scaleUnit").val(usca);
                uploadFile.onComplete(imgList,'');
                initMap();
            }

        },
        error:function (err) {
            console.log("获取农场出错！");
        }
    });
}